package com.ny.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class LoginDemo {

    private static final String URL = "jdbc:mysql://localhost:3306/sbssj";
    private static final String SJ_USERNAME = "root";
    private static final String SJ_PASSWORD = "123456";

    public static void main(String[] args) {
        // 用户输入
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名: ");
        String username = scanner.next();
        System.out.print("请输入密码: ");
        String password = scanner.next();

        // 登录验证
        if (login(username, password)) {
            System.out.println("登录成功!");
        } else {
            System.out.println("登录失败!");
        }

        scanner.close();
    }

    private static boolean login(String username, String password) {
        String sql = "SELECT * FROM sbssj WHERE username = ? AND password = ?";

        try (Connection connection = DriverManager.getConnection(URL, SJ_USERNAME, SJ_PASSWORD);
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);

            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                return resultSet.next(); // 如果有结果，表示登录成功
            }

        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}

